<?php
namespace app\ausagent\controller;
use app\ausagent\controller\Common;
use think\Db;
use think\Controller;
use Godok\Org\Auth;
use think\Config;

class Index extends Common
{
    /**
     * 控制台
     */
    // http://127.0.0.1/ausagent/Index/index
    public function index()
    {
        $groupids = \Godok\Org\Auth::user('groupids');
        $data = ['groupname'=>'游客'];
        if( !empty($groupids) ) {
           // var_dump($groupids);die;
            $group = Db::name( Config::get('auth.table_group') )->where(['id' => $groupids[0]])->find();
            if ( $group ) {
                $data['groupname'] = $group['title'];
            }
        }
        $data['menu'] = $this->menu2Html( \Godok\Org\Auth::menu("ismenu=1 AND status=1") );

		return $this->fetch('index',$data);
    }
    
    /**
     * 首页
     */
    public function home(){
        $where = 'is_delete = 1 AND oid = '.session('oid');
        //当月总充值余额
        $recharge = Db::name( 'rechargeorder')
                ->whereTime('payment_date', 'month')
                ->where($where)
                ->sum('balance');
        if($recharge==''){
            $recharge = 0;
        }

        //总租金额
        $sumRent = Db::name('leaseorder')->whereTime('create_time', 'month')->where($where)->sum('amount');
        if($sumRent==''){
            $sumRent = 0;
        }
        //总商户数
        $sumSeller = DB::name('seller') ->where($where)-> count();      
        //总用户数
        $sumUser = Db::name('user')->where($where)->count();

        //-->本周统计
        //本周总充值余额
        $time = gettimestamp('thisweek');
        $rsearch['oid'] = session('oid');
        $rsearch['is_delete'] = 1;
        $rsearch['payment_date'] = array(array('egt',$time['starttime']),array('elt',$time['endtime']), 'and');
        $weekRecharge = Db::name('rechargeorder')
                      ->where($rsearch)
                      ->field("FROM_UNIXTIME(payment_date,'%d') as unit,sum(balance) as amount")
                      ->group("unit")
                      ->select(); 
        //本周总租金额
        $wl['oid'] = session('oid');
        $wl['is_delete'] = 1;
        $wl['create_time'] = array(array('egt',$time['starttime']),array('elt',$time['endtime']), 'and');
        $weekRent = Db::name('leaseorder')
                      ->where($wl)
                      ->field("FROM_UNIXTIME(create_time,'%d') as unit,ifnull(sum(amount),0) as amount")
                      ->group("unit")
                      ->select();
        ///echo Db::name('leaseorder')->getlastsql();

        //本周有效订单总数
        $where .= " AND trade_no != ''" ;
        //本周有效订单数
        $weekSumOrder = Db::name( 'rechargeorder')
                       ->whereTime('create_time', 'week')
                       ->where($where)
                       ->count();
        //本月有效订单数
        $monthSumOrder = Db::name( 'rechargeorder')
               ->whereTime('create_time', 'month')
               ->where($where)
               ->count();
        //总订单数 包括未支付等
        $allOrder = DB::name('rechargeorder')
                  ->where('oid',session('oid'))
                  ->count();
                           
        //有效订单总数
        $effectiveAllOrder = DB::name('rechargeorder')
                           ->where($where)
                           ->count();
         //有效总订单百分比
         if(!$allOrder and !$effectiveAllOrder){
            $allOrder = 0;
            $effectiveAllOrder = 0;
            $allOrderAvg = 0;
         }else{
            $allOrderAvg = sprintf("%.2f", $effectiveAllOrder/$allOrder)*100;
        }
        
        if(!$monthSumOrder){
            $monthSumOrder = 0;
            $monthOrderAvg = 0;
        }else{
         //有效订单本月百分比
         $monthOrderAvg = sprintf("%.2f", $monthSumOrder/$allOrder)*100;
        } 

        if(!$weekSumOrder or !$monthSumOrder){
            $weekSumOrder = 0;
            $avg = 0;
        }else{
         //有效订单本周百分比
            $avg =  sprintf("%.2f", $weekSumOrder/$monthSumOrder); 

        }
         //总租借记录
         $leaseAllOrder = Db::name('leaseorder')
                        ->where('is_delete',1)
                        ->where('oid',session('oid'))
                        ->count();
        //本月租借次数
        $leaseSumOrder = Db::name('leaseorder')
                        ->whereTime('create_time', 'month')
                        ->where('is_delete',1)
                        ->where('oid',session('oid'))
                        ->where('status',2)
                        ->count();
        if(!$leaseSumOrder){
            $leaseSumOrder = 0;
            $leaseMonthAvg = 0;
        }else{
        //本月占总数的百分比
            $leaseMonthAvg = sprintf("%.2f", $leaseSumOrder/$leaseAllOrder)*100;                 
        }
        //用户状态列表
        $u = 'user';//定义用户表
        $userStatus = Db::name('leaseorder')
                    ->alias('a')
                    ->join("$u b",'a.oid = b.oid and a.uid = b.id')
                    ->field('a.id,a.order_no,a.amount,a.status,a.create_time,b.name')
                    ->where('a.oid',session('oid'))
                    ->order('a.create_time desc')
                    ->limit(10)
                    ->select();

        //商户营业额
        $b = 'leaseorder';
        $sellerTurnover = Db::name('seller')
                        ->alias('a')
                        ->whereTime($b.'.create_time', 'month')
                        ->join($b,'a.id = '.$b.'.sid')//线上用别名报错aushare.[别名]不存在
                        ->field("sum(".$b.".amount) as amount,a.name as name,a.area")
                        ->where('a.oid',session('oid'))
                        ->group("name,a.area")
                        ->limit(10)
                        ->select();       
//        dump($sellerTurnover); die;


        //整合成数组
        $data = array(
                'recharge'        =>   $recharge,
                'sumRent'         =>   $sumRent,
                'sumSeller'       =>   $sumSeller,
                'sumUser'         =>   $sumUser,
                'monthSumOrder'   =>   $monthSumOrder,
                'monthOrderAvg'   =>   $monthOrderAvg,
                'leaseSumOrder'   =>   $leaseSumOrder,
                'leaseMonthAvg'   =>   $leaseMonthAvg,
                'effectiveAllOrder' => $effectiveAllOrder,
                'allOrderAvg'     =>   $allOrderAvg                
            );
        $this->assign('v',$data);
        $this->assign('wr',$weekRecharge);
        $this->assign('wrant',$weekRent);
        $this->assign('us',$userStatus);
        $this->assign('st',$sellerTurnover);
        
        return $this->fetch();
    }

    /**
     * 格式化菜单
     */
    private  function menu2Html($list,$level = 0)
    {
        $menu = '';
        $menulevel = ['first','second','third'];
        if ( is_array($list) ) {
            if( $level > 2 ) {
                $level = 2;
            }
            $menu .= $level > 0  ? '<ul class="nav nav-'.$menulevel[$level].'-level">' : '';

            foreach ( $list as $li ) {
                $menu .= '<li>';
                if( empty($li['module']) || empty($li['controller']) || '*' == $li['module'] || '*' == $li['controller'] ) {
                    $menu .= '<a href="javascript:void(0)" >';
                } else {
                    $act = explode(',',$li['action']);
                    $href = \think\Request::instance()->root().'/'. $li['module'] . '/' . $li['controller'] . '/' . $act[0];
                    if( !empty($li['condition']) ) {
                        $href .= '?' . $li['condition'];
                    }
                    $menu .= '<a href="' . $href . '" class="J_menuItem">';
                }
    
                if ( !empty($li['icon']) ) {
                    $menu .= '<i class="' . $li['icon'] . '"></i> ';
                }
                $menu .= '<span class="nav-label">' . lang($li['title']) . '</span>';
                if ( isset($li['children']) ) {
                    $children = $this->menu2Html($li['children'], $level + 1 );
                    $menu .= ' <span class="fa arrow"></span>';
                } else {
                    $children = '';
                }
                $menu .= '</a>' . $children;
                $menu .= '</li>';
            }
    
            $menu .= $level > 0 ? '</ul>' : '';
            return $menu;
        } else {
            return '';
        }
    }

    public function ceshi(){

    }

    public function default(){

        $groupids = \Godok\Org\Auth::user('groupids');
        $data = ['groupname'=>'游客'];
        if( !empty($groupids) ) {
           // var_dump($groupids);die;
            $group = Db::name( Config::get('auth.table_group') )->where(['id' => $groupids[0]])->find();
            if ( $group ) {
                $data['groupname'] = $group['title'];
            }
        }
        $data['menu'] = $this->menu2Html( \Godok\Org\Auth::menu("ismenu=1 AND status=1") );

        return $this->fetch('default',$data);
    }

    
}
